const { exec } = require('../db/mysql')


//处理获取博客列表
const getList = (author, keyword) => {
    // console.log(author)
    let sql = `select * from blogs where 1=1 `
    if (author) {
        sql += `and author ='${author}' `
    }
    if (keyword) {
        sql += `and title like '%${keyword}%' `
    }
    sql += `order by createtime desc; `
    // console.log(sql)
    //返回promise
    return exec(sql)
}

//获取博客详情
const getDetail = (id) => {
    let sql = `select * from blogs where 1=1 `
    if (id) {
        sql += `and id =${id} `
    }
    
    sql += `order by createtime desc; `

    //返回promise
    return exec(sql)
}

//新增博客
const newBlog = (blogData = {}) => {
    //blogData是一个博客对象，包含title content属性
    const title=blogData.title
    const author=blogData.author
    const content=blogData.content
    const createtime=Date.now()

    const sql = `
        insert into blogs (title,author,content,createtime) values ('${title}','${author}','${content}','${createtime}')
    `
    return exec(sql).then(insertData=>{
        console.log('insertData is',insertData)
        return {
            id:insertData.insertId
        }
    })
}

//更新博客
const updateBlog = (id, blogData = {}) => {
    // console.log(id,blogData)
    //id就是要更新博客的id
    //blogData是一个博客对象，包含title content属性
    const title=blogData.title
    const content=blogData.content

    const sql = `update blogs set title='${title}',content='${content}' where id='${id}'`
    console.log(sql)
    return exec(sql).then(upDate=>{
        console.log('upDate is',upDate)
        if(upDate.affectedRows>0){
            return true
        }
        return false
    })
    // console.log('update blog', id, blogData)
    // return true
}

//删除博客
const deleteBlog = (id,author) => {

    const sql=`delete from blogs where id='${id}' and author='${author}'`
    console.log(sql)
    return exec(sql).then(delData=>{
        console.log('delData is',delData)
        if(delData.affectedRows>0){
            return true
        }
        return false
    })
    // console.log('id:', id)
    // return true
}





module.exports = {
    getList,
    getDetail,
    newBlog,
    updateBlog,
    deleteBlog
}










